import wxValidate from 'wechat-validate'
const app = getApp()
Page({
  data:{
    mobile:'',
    password:'',
    returnUrl:''
  },
  onLoad(options){
    const pages = getCurrentPages()
    const currentPage = pages.pop()
    console.log(currentPage.route);
    this.setData({
      returnUrl:currentPage.route
    })
  },
  behaviors:[wxValidate],
  rules:{
    mobile:[
      {required:true,message:'请输入手机号'},
      {pattern:/^1[3-8]\d{9}$/,message:'请输入正确的手机号'}
    ],
    password:[
      {required:true,message:'请输入密码'},
      {pattern:/^\w{6}$/,message:'请输入正确的密码'}
    ]
  },
    // 表单校验
    btnMobile(){
      const {valid,message} = this.validate('mobile')
      if(!valid) return wx.utils.toast(message)
    },
    btnPassword(){
      const {valid,message} = this.validate('password')
      if(!valid) return wx.utils.toast(message)
    },
    // 提交表单
    async submitBtn(){
      if(!this.validate()) return wx.utils.toast('密码或手机号输入不正确')
      const {errno,data}  = await wx.http.post('/index/login',{
        mobile:this.data.mobile,
        password:this.data.password
      })
      if(errno !==0) return wx.utils.toast('登录失败，请稍后重试')
      // 登录成功，存储token
      app.setToken('token',data.token)
      wx.reLaunch({
        url:'/pages/user/user' ,
      })
    }
})